// buffer: Float32Array，范围 -1~1
// sampleRate: 采样率（如 44100）
export function analyzeFrequency(buffer, sampleRate) {
	const SIZE = buffer.length;
	let rms = 0;
	for (let i = 0; i < SIZE; i++) {
		rms += buffer[i] * buffer[i];
	}
	rms = Math.sqrt(rms / SIZE);
	console.log('RMS:', rms);
	if (rms < 0.005) return -1;

	let maxShift = Math.floor(SIZE / 2);
	let bestOffset = -1;
	let bestCorrelation = 0;
	let correlations = new Array(maxShift);

	for (let offset = 16; offset < maxShift; offset++) {
		let correlation = 0;
		for (let i = 0; i < maxShift; i++) {
			correlation += buffer[i] * buffer[i + offset];
		}
		correlations[offset] = correlation;
		if (correlation > bestCorrelation) {
			bestCorrelation = correlation;
			bestOffset = offset;
		}
	}

	console.log('bestCorrelation:', bestCorrelation, 'bestOffset:', bestOffset);

	if (bestCorrelation > 0.001 && bestOffset > 0) {
		let shift = 0;
		if (bestOffset > 0 && bestOffset < correlations.length - 1) {
			let y1 = correlations[bestOffset - 1];
			let y2 = correlations[bestOffset];
			let y3 = correlations[bestOffset + 1];
			const denominator = 2 * (2 * y2 - y1 - y3);
			if (denominator !== 0) {
				shift = (y3 - y1) / denominator;
			}
		}
		let estimatedPeriod = bestOffset + shift;
		if (estimatedPeriod > 0) {
			return sampleRate / estimatedPeriod;
		}
	}
	return -1;
}